﻿// ***********************************************************************
// Assembly         : MVC4Portal
// Author           : Lolo
// Created          : 09-21-2013
//
// Last Modified By : Lolo
// Last Modified On : 11-12-2013
// ***********************************************************************
// <copyright file="ForgotPasswordController.cs" company="">
//     Copyright (c) . All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System.Configuration;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using InnovaApp.Layers.DataLayer;
using InnovaApp.Layers.ResourcesLayer.Properties;
using InnovaApp.Layers.SecurityLayer.Models;
using InnovaApp.Layers.SecurityLayer.Models.AccountModels.MembershipServices;
using InnovaApp.Layers.SecurityLayer.Models.ViewModels._LayoutViewModels;
using INNOVACALL.Framework.Common;
using INNOVACALL.Framework.Common.Models;
using InnovaApp.Portals.MVC4Portal.Models.ViewModels.LayoutViewModels.SecurityViewModels;
using InnovaApp.Layers.CommonLayer;
using INNOVACALL.Framework.Common.MVCHelpers.Localization;

namespace InnovaApp.Portals.MVC4Portal.Controllers.ViewControllers.LayoutViewControllers.SecurityControllers
{
    /// <summary>
    /// Class ForgotPasswordController
    /// </summary>
    public class ForgotPasswordController : _SecurityControllers_Base<ForgotPassword_ViewModel>
    {
        /// <summary>
        /// Gets or sets the forms service.
        /// </summary>
        /// <value>The forms service.</value>
        public IFormsAuthenticationService FormsService { get; set; }
        /// <summary>
        /// Gets or sets the membership service.
        /// </summary>
        /// <value>The membership service.</value>
        public IMembershipService MembershipService { get; set; }

        /// <summary>
        /// Initializes data that might not be available when the constructor is called.
        /// </summary>
        /// <param name="requestContext">The HTTP context and route data.</param>
        protected override void Initialize(RequestContext requestContext)
        {
            base.eMethodBase = "InnovaApp.Layers.SecurityLayer.Controllers.ForgotPasswordController";
            base.specificCssCollection = new string[] { "Views/Account/AccountCommon.css", "ClientComponents/KendoUI/kendo." + PortalEnvironment.KendoUITheme + ".min.css" };
            base.specificJSCollection = null;
            base.dynamicJSCollection = new string[] { "/ScriptsG/ForgotPasswordDynamic.js" };
            base.specificJqueryJSCollection = new string[] { "Views/ForgotPassword.js" };
            base.externalCss = null;
            base.Meta.Add(enMeta.Description, Resources.View_ForgotPassword_Meta_Description);
            base.Meta.Add(enMeta.Keywords, Resources.View_About_Meta_Keywords);
            base.Meta.Add(enMeta.Subject, Resources.View_ForgotPassword_Meta_Subject);

            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        /// <summary>
        /// Selects the language.
        /// </summary>
        /// <returns>ActionResult.</returns>
        public ActionResult SelectLanguage()
        {
            return Redirect(string.Format("/{0}{1}", base.URLReferLanguage, Request.Url.PathAndQuery));
        }

        /// <summary>
        /// URL[Get]: /ForgotPassword
        /// </summary>
        /// <returns>ActionResult.</returns>
        [HttpGet]
        public ActionResult Index()
        {
            string language = base.URLReferLanguage;
            base.LocalizeDynamicScript(language, (CurrentContact != null ? CurrentContact.FavoriteLanguage.Language : null));
            using (DataRepositories _dataContext = new DataRepositories())
            {
                base.InitView(
                    pageTitle: Resources.View_ForgotPassword_PageTitle,
                    openingMessage: string.Empty,
                    specificCssCollection: specificCssCollection,
                    specificJSCollection: specificJSCollection,
                    dynamicJSCollection: dynamicJSCollection,
                    specificJqueryJSCollection: specificJqueryJSCollection,
                    jsVariables: jsVariables,
                    externalJs: externalJs,
                    externalCss: externalCss,
                    metaToAdd: Meta,
                    _dataContext: _dataContext,
                    displayMenus: false,
                    language: base.URLReferLanguage,
                    adminMode: false,
                    usesKendoUI: true,
                    jQueryUITheme: null,
                    kendoUITheme: null,
                    currentUser: Membership.GetUser()
                    );
            }

            return View(ContentData);
        }

        /// <summary>
        /// URL[Post]: /ForgotPassword
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns>JsonResult.</returns>
        [HttpPost]
        public JsonResult Index(ForgotPassword_ViewModel model)
        {
            JsonResult toReturn = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            string logMessage = string.Empty;
            string userName = Membership.GetUserNameByEmail(model.EMailAddress.ToLower());
            if (!string.IsNullOrEmpty(userName))
            {
                MembershipUser user = Membership.GetUser(userName);
                LandingPageSecurityParameters landingPageSecurityParameters = new LandingPageSecurityParameters() { userCreationDate = user.CreationDate.ToString(), userEMail = user.Email, username = user.UserName };

                if (SendPasswordResetEMail(landingPageSecurityParameters,ref logMessage)) {
                    toReturn.Data = new { 
                        @success = true, 
                        @messageTitle = Resources.View_All_cap_OpeningMessageTitle, 
                        @message = Resources.View_ForgotPassword_CheckEmail, 
                        @scriptToExecute = "$.fn.jqDialogAlert(a.messageTitle, a.message, '/', 400,90);" 
                    };
                } else {
                    toReturn.Data = new { 
                        @success = false, 
                        @messageTitle = Resources.View_All_cap_OpeningMessageTitle, 
                        @message = Resources.View_ForgotPassword_FailSendingEMail, 
                        @scriptToExecute = "$.fn.jqDialogAlert(a.messageTitle, a.message, '/', 400,90);" 
                    };
                }
            }
            else {
                toReturn.Data = new { 
                    @success = false, 
                    @messageTitle = 
                    Resources.View_All_cap_OpeningMessageTitle, 
                    @message = Resources.View_ForgotPassword_EMailNotFound,
                    @scriptToExecute = "$.fn.jqDialogAlert(a.messageTitle, a.message, '/', 400,90);" 
                };
            }
            return toReturn;
        }

        /// <summary>
        /// Activation EMail sender
        /// </summary>
        /// <param name="sendActivationEmailParameters">The send activation email parameters.</param>
        /// <param name="logMessage">The log message.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        private bool SendPasswordResetEMail(LandingPageSecurityParameters sendActivationEmailParameters, ref string logMessage)
        {
            bool toReturn = true;
            object eMethodParameters = new { @userEMail = sendActivationEmailParameters.userEMail, @userCreationDate = sendActivationEmailParameters.userCreationDate, @username = sendActivationEmailParameters.username };
            string landingPageAddress = string.Empty;
            string messageSubject = string.Format(Resources.View_ForgotPassword_EMail_Subject, this.SiteBaseURL);
            string messageBody = string.Empty;
            landingPageAddress = base.SendMailSecurizedLandingPageBuilder(enLandingPages.ResetForgottenPassword, base.URLReferLanguage, sendActivationEmailParameters.userEMail, sendActivationEmailParameters.userCreationDate);
            messageBody += Resources.View_ForgotPassword_EMail_Body1 + "\n<br/>";
            messageBody += "<a href=\"" + landingPageAddress + "\">" + Server.HtmlEncode(Resources.View_ForgotPassword_ClickHereToProceed) + "</a><br/>";
            messageBody += Resources.View_ForgotPassword_EMail_Body2 + "\n<br/>";
            toReturn = base.SendMail(string.Empty, sendActivationEmailParameters.userEMail, sendActivationEmailParameters.username, messageSubject, true, messageBody);
            logMessage += "Activation mail sent\n";
            toReturn = base.SendMail(string.Empty, sendActivationEmailParameters.userEMail, sendActivationEmailParameters.username, messageSubject, true, messageBody);
            return toReturn;
        }

    }
}
